package com.gs.gulishopp.gulishoppproduct.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gs.common.utils.PageUtils;
import com.gs.common.utils.Query;

import com.gs.gulishopp.gulishoppproduct.dao.CategoryDao;
import com.gs.gulishopp.gulishoppproduct.entity.CategoryEntity;
import com.gs.gulishopp.gulishoppproduct.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查询所有产品分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        //组装父子分类 树状
        //1.找到找到所有的一级分类 parentCid为0
        List<CategoryEntity> collect = categoryEntities.stream().
                filter(category -> category.getParentCid() == 0).map(meum->{
                    meum.setChildren(getCategorys(meum,categoryEntities));
                    return meum;
        }).sorted((meum1,meum2)->{
            return (meum1.getSort() == null ?0:meum1.getSort()) - (meum2.getSort() == null ?0:meum2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

    /**
     * 递归查询所有子类
     * @param current 当前分类
     * @param all 所有分类
     * @return
     */
    public List<CategoryEntity> getCategorys(CategoryEntity current,List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream().filter(category -> category.getParentCid() == current.getCatId()).
                map(meum -> {
                    //找到子产品分类
                    meum.setChildren(getCategorys(meum, all));
                    return meum;
                }).sorted((meum1, meum2) -> {
            return (meum1.getSort() == null ?0:meum1.getSort()) - (meum2.getSort() == null ?0:meum2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

}